package public

import (
	"github.com/e421083458/golang_common/lib"
	"github.com/garyburd/redigo/redis"
	"os"
)

type RedisInfo struct {
	Key   string
	Value string
	Exp   int64
}

//SetToRedis 存入redis
func SetToRedis(info RedisInfo) error {
	trace := lib.NewTrace()
	tx, err := lib.RedisConnFactory("default")
	if err != nil {
		return err
	}
	defer tx.Close()
	lib.RedisLogDo(trace, tx, "SET", info.Key, info.Value)
	if info.Exp != 0 {
		lib.RedisLogDo(trace, tx, "expire", info.Key, info.Exp)
	}
	return nil
}

//GetToRedis 取出redis
func GetToRedis(info RedisInfo) (string, error) {
	trace := lib.NewTrace()
	tx, err := lib.RedisConnFactory("default")
	if err != nil {
		return "", err
	}
	defer tx.Close()
	v, err := redis.String(lib.RedisLogDo(trace, tx, "GET", info.Key))
	if err != nil {
		return "", err
	}
	return v, nil
}

//CreateFile 创建文件
func CreateFile(name string, data []byte, isAppend bool) (err error) {
	oflag := os.O_CREATE | os.O_WRONLY
	if isAppend {
		oflag |= os.O_APPEND
	} else {
		oflag |= os.O_TRUNC
	}

	file, err := os.OpenFile(name, oflag, 0600)
	if err != nil {
		return
	}
	defer file.Close()

	_, err = file.Write(data)
	return
}
